package de.axone.wash.handler;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import de.axone.wash.Wash;
import de.axone.wash.Wash.NotFoundException;
import de.axone.wash.Wash.WrongTypeException;
import de.axone.wash.configuration.Configuration;
import de.axone.wash.service.Service;


public class DefaultHandler implements Handler {
	
	private HashMap<String, Service> services;
	
	public DefaultHandler(){}
	
	public void init( Configuration config ) throws HandlerException {
		
		services = new HashMap<String, Service>();
		
		Wash configWash = config.getWash();
		
		int i = 0;
		while( true ) {
			
			try {
				
				String base = "service-" + i;
				
				if( ! configWash.hasField(  base + ".name" ) )
					break;
				
				String serviceName = configWash.getString( base + ".name" );
				String className   = configWash.getString( base + ".class" );
				
				Service service = (Service)Class.forName( className ).newInstance();
				
				services.put( serviceName, service );
				
			} catch( WrongTypeException e ) {
				 throw new HandlerException( e );
				
			} catch( InstantiationException e ) {
				 throw new HandlerException( e );
				
			} catch( IllegalAccessException e ) {
				 throw new HandlerException( e );
				
			} catch( ClassNotFoundException e ) {
				 throw new HandlerException( e );
				 
			} catch( NotFoundException e ) {
				 throw new HandlerException( e );
			}
			
			i++;
		}
		if( i == 0 ) System.err.println( "No Service in service.wash. Check service.X entry musst start with service.0" );
	}

	public Wash handle( Wash request, HttpServletRequest httpRequest ) throws HandlerException {
		
		Service service;
		Wash result = null;
		try {
			System.err.println( request.getString( "wash.service" ) );
			service = services.get( request.getString( "wash.service" ) );
		
			if( service == null )
				throw new NotFoundException();
			
			result = service.service( request, httpRequest );
		
		} catch( NotFoundException e ) {
			throw new ServiceNotFoundException();
		} catch( WrongTypeException e ) {
			throw new ServiceNotFoundException();
		}
		
		return result;
	}
}
